package com.wz.jaav.classreader.classFile;

import com.wz.jaav.classreader.ClassReader;
import com.wz.jaav.classreader.classFile.attribute.Attribute;
import com.wz.jaav.classreader.classFile.constant.ConstantInfo;
import com.wz.jaav.util.CommonUtils;

import java.util.Arrays;

public class MethodInfo {
    //单纯计数用，非文件属性
    private short count;

    private short accessFlag;
    private short nameIndex;
    private short descriptorIndex;
    private short attributeCount;
    private Attribute[] attributes;

    public void build(ClassReader cr) {
        byte[] af = cr.doRead(2);
        System.out.println("method read:" + CommonUtils.bytesToHex(af));
        accessFlag = CommonUtils.byteToShort(af);
        byte[] ni = cr.doRead(2);
        System.out.println("method read:" + CommonUtils.bytesToHex(ni));
        nameIndex = CommonUtils.byteToShort(ni);
        byte[] di = cr.doRead(2);
        System.out.println("method read:" + CommonUtils.bytesToHex(di));
        descriptorIndex = CommonUtils.byteToShort(di);
        byte[] ac = cr.doRead(2);
        System.out.println("method read:" + CommonUtils.bytesToHex(ac));
        attributeCount = CommonUtils.byteToShort(ac);
        attributes = new Attribute[attributeCount];
        for (int i = 0; i < attributeCount; i++) {
            Attribute attribute = new Attribute();
            attribute.build(cr);
            attributes[i] = attribute;
            count++;
        }
    }

    public short getNameIndex() {
        return nameIndex;
    }

    public Attribute[] getAttributes() {
        return attributes;
    }

    @Override
    public String toString() {
        String str = "    MethodInfo{" +
                "accessFlag=" + accessFlag +
                ", nameIndex=" + nameIndex +
                ", descriptorIndex=" + descriptorIndex +
                ", attributeCount=" + attributeCount +
                '}';
        return str;
    }

    public void printInfos() {
        System.out.println(toString());
        for (int i = 0; i < attributes.length; i++) {
            if (attributes[i] != null) {
                System.out.println("        id:" + i + "--" );
                attributes[i].printInfos("        ");
            }
        }
    }
}